package com.zzyweb.rentalcarsys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyweb.rentalcarsys.entity.News;
import com.zzyweb.rentalcarsys.exception.BusinessException;
import com.zzyweb.rentalcarsys.exception.ErrorCode;
import com.zzyweb.rentalcarsys.mapper.NewsMapper;
import com.zzyweb.rentalcarsys.service.NewsService;
import com.zzyweb.rentalcarsys.utils.PageResult;
import jakarta.validation.constraints.Max;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhiyi
 * @date 9/30/25
 **/
@Service
public class NewsServiceImpl implements NewsService {
    @Autowired
    NewsMapper newsMapper;
    @Override
    public PageResult<News> getAllNews(Long currentPage, Long pageSize, News news) {
        Page<News> page = new Page<>(currentPage, pageSize);
        QueryWrapper<News> newsQueryWrapper = new QueryWrapper<>();
        if (news != null) {
            newsQueryWrapper.like(StringUtils.hasText(news.getTitle()),"title", news.getTitle())
                    .like(StringUtils.hasText(news.getContent()),"content", news.getContent())
                    .like(StringUtils.hasText(news.getAuthor()),"author", news.getAuthor());

        }
        newsQueryWrapper.orderByDesc("publish_date");
        List<News> newsList = newsMapper.selectList(page, newsQueryWrapper);

        PageResult<News> pageResult = new PageResult<>(currentPage,pageSize,page.getTotal(),newsList);
        return pageResult;
    }

    @Override
    public void modifyNews(News news) {
        int row = newsMapper.updateById(news);
        if (row != 1) {
            throw new BusinessException(ErrorCode.FAIL);
        }
    }

    @Override
    public void deleteNewsById(String newsId) {
        Long idInLong = Long.parseLong(newsId);
        int row = newsMapper.deleteById(idInLong);
        if (row != 1) {
            throw new BusinessException(ErrorCode.FAIL);
        }
    }

    @Override
    public void deleteNewsBatch(String ids) {
        if (!StringUtils.hasText(ids)) throw new BusinessException(ErrorCode.FAIL);
        String[] split = ids.split(",");
        List<String> idsList = Arrays.asList(split);
        List<Long> idsListAsLong = idsList.stream().map(s -> Long.parseLong(s))
                        .collect(Collectors.toList());
        int row = newsMapper.deleteByIds(idsListAsLong);
        if (row == 0) {
            throw new BusinessException(ErrorCode.FAIL);
        }
    }

    @Override
    public Long addNews(News news) {
        int row = newsMapper.insert(news);
        if (row != 1) {
            throw new BusinessException(ErrorCode.FAIL);
        }
        return news.getNewsId();
    }
}
